<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// --- 数据定义 ---
const route = useRoute()
const activeTab = ref('attackRecords') // 默认显示犯病记录

const patientId = ref(null) // 当前查看的患者ID

// 犯病记录列表和表单数据
const attackRecords = ref([])
const attackForm = reactive({
  recordId: null,
  userId: null,
  attackDate: null,
  attackType: '',
  attackDuration: '',
  notes: '',
})
const attackFormDialogVisible = ref(false)
const isAttackEditing = ref(false) // 是否处于犯病记录编辑模式
const attackFormRef = ref(null)

// 药物不良反应记录列表和表单数据
const reactionRecords = ref([])
const reactionForm = reactive({
  recordId: null,
  userId: null,
  reactionDate: null,
  reactionDescription: '',
  medicationInvolved: '',
  severity: '', // 严重程度
  notes: '',
})
const reactionFormDialogVisible = ref(false)
const isReactionEditing = ref(false) // 是否处于药物不良反应编辑模式
const reactionFormRef = ref(null)

// --- 表单校验规则 ---
const attackRules = reactive({
  attackDate: [{ required: true, message: '请选择犯病日期', trigger: 'change' }],
  attackType: [{ required: true, message: '请输入犯病类型', trigger: 'blur' }],
  attackDuration: [{ required: true, message: '请输入犯病持续时间', trigger: 'blur' }],
})

const reactionRules = reactive({
  reactionDate: [{ required: true, message: '请选择反应日期', trigger: 'change' }],
  reactionDescription: [{ required: true, message: '请输入反应描述', trigger: 'blur' }],
  medicationInvolved: [{ required: true, message: '请输入涉及药物', trigger: 'blur' }],
  severity: [{ required: true, message: '请选择严重程度', trigger: 'change' }],
})

// --- 通用方法 ---
const getPatientIdFromRoute = () => {
  // 假设 patientId 是通过路由参数传递的，例如 /home/symptoms/:patientId
  // 或者通过查询参数传递，例如 /home/symptoms?patientId=123
  // 这里我们假设通过查询参数获取，因为医生可能从患者列表点击过来
  patientId.value = route.query.patientId ? parseInt(route.query.patientId) : null;
  // 如果没有 patientId，医生可能需要先选择一个患者
  if (!patientId.value) {
    ElMessage.warning('请先选择一个患者来查看症状及不良反应记录。');
    // 可以重定向到患者列表页面
    // router.push('/home/patients');
  }
}

// --- 犯病记录相关方法 ---

// 获取犯病记录列表
const fetchAttackRecords = async () => {
  if (!patientId.value) return;
  try {
    const response = await axios.get(`http://localhost:8080/patient-attack/user/${patientId.value}`)
    if (response.data.code === 200) {
      attackRecords.value = response.data.data
    } else {
      ElMessage.error(`获取犯病记录失败: ${response.data.msg}`)
    }
  } catch (error) {
    console.error('获取犯病记录时发生错误:', error)
    ElMessage.error('获取犯病记录失败，请检查网络。')
  }
}

// 打开添加犯病记录对话框
const openAddAttackDialog = () => {
  resetAttackForm()
  attackForm.userId = patientId.value // 自动填充患者ID
  isAttackEditing.value = false
  attackFormDialogVisible.value = true
}

// 打开编辑犯病记录对话框
const openEditAttackDialog = (record) => {
  Object.assign(attackForm, structuredClone(record)) // 深拷贝 record
  isAttackEditing.value = true
  attackFormDialogVisible.value = true
}

// 提交犯病记录表单 (添加/更新)
const submitAttackForm = async () => {
  try {
    await attackFormRef.value.validate()
    let response;
    if (isAttackEditing.value) {
      // 更新犯病记录
      response = await axios.put('http://localhost:8080/patient-attack', attackForm)
    } else {
      // 添加犯病记录
      response = await axios.post('http://localhost:8080/patient-attack', attackForm)
    }

    if (response.data.code === 200) {
      ElMessage.success(`${isAttackEditing.value ? '更新' : '添加'}犯病记录成功！`)
      attackFormDialogVisible.value = false
      fetchAttackRecords() // 刷新列表
    } else {
      ElMessage.error(`${isAttackEditing.value ? '更新' : '添加'}犯病记录失败: ${response.data.msg}`)
    }
  } catch (error) {
    console.error('提交犯病记录时发生错误:', error)
    if (error.isAxiosError) {
      ElMessage.error('提交失败，请检查网络或服务器。')
    } else {
      ElMessage.error('表单校验失败，请检查输入项。')
    }
  }
}

// 删除犯病记录
const deleteAttackRecord = async (recordId) => {
  ElMessageBox.confirm('确定要删除这条犯病记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await axios.delete(`http://localhost:8080/patient-attack/${recordId}`)
      if (response.data.code === 200) {
        ElMessage.success('犯病记录删除成功！')
        fetchAttackRecords() // 刷新列表
      } else {
        ElMessage.error(`删除犯病记录失败: ${response.data.msg}`)
      }
    } catch (error) {
      console.error('删除犯病记录时发生错误:', error)
      ElMessage.error('删除犯病记录失败，请检查网络。')
    }
  }).catch(() => {
    ElMessage.info('已取消删除。')
  })
}

// 重置犯病记录表单
const resetAttackForm = () => {
  attackFormRef.value?.resetFields()
  Object.assign(attackForm, {
    recordId: null,
    userId: null,
    attackDate: null,
    attackType: '',
    attackDuration: '',
    notes: '',
  })
}

// --- 药物不良反应相关方法 ---

// 获取药物不良反应记录列表
const fetchReactionRecords = async () => {
  if (!patientId.value) return;
  try {
    const response = await axios.get(`http://localhost:8080/api/patient-reaction/user/${patientId.value}`)
    if (response.data.code === 200) {
      reactionRecords.value = response.data.data
    } else {
      ElMessage.error(`获取药物不良反应记录失败: ${response.data.msg}`)
    }
  } catch (error) {
    console.error('获取药物不良反应记录时发生错误:', error)
    ElMessage.error('获取药物不良反应记录失败，请检查网络。')
  }
}

// 打开添加药物不良反应对话框
const openAddReactionDialog = () => {
  resetReactionForm()
  reactionForm.userId = patientId.value // 自动填充患者ID
  isReactionEditing.value = false
  reactionFormDialogVisible.value = true
}

// 打开编辑药物不良反应对话框
const openEditReactionDialog = (record) => {
  Object.assign(reactionForm, structuredClone(record)) // 深拷贝 record
  isReactionEditing.value = true
  reactionFormDialogVisible.value = true
}

// 提交药物不良反应表单 (添加/更新)
const submitReactionForm = async () => {
  try {
    await reactionFormRef.value.validate()
    let response;
    if (isReactionEditing.value) {
      // 更新药物不良反应记录
      response = await axios.put('http://localhost:8080/api/patient-reaction', reactionForm)
    } else {
      // 添加药物不良反应记录
      response = await axios.post('http://localhost:8080/api/patient-reaction', reactionForm)
    }

    if (response.data.code === 200) {
      ElMessage.success(`${isReactionEditing.value ? '更新' : '添加'}药物不良反应记录成功！`)
      reactionFormDialogVisible.value = false
      fetchReactionRecords() // 刷新列表
    } else {
      ElMessage.error(`${isReactionEditing.value ? '更新' : '添加'}药物不良反应记录失败: ${response.data.msg}`)
    }
  } catch (error) {
    console.error('提交药物不良反应时发生错误:', error)
    if (error.isAxiosError) {
      ElMessage.error('提交失败，请检查网络或服务器。')
    } else {
      ElMessage.error('表单校验失败，请检查输入项。')
    }
  }
}

// 删除药物不良反应记录
const deleteReactionRecord = async (recordId) => {
  ElMessageBox.confirm('确定要删除这条药物不良反应记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await axios.delete(`http://localhost:8080/api/patient-reaction/${recordId}`)
      if (response.data.code === 200) {
        ElMessage.success('药物不良反应记录删除成功！')
        fetchReactionRecords() // 刷新列表
      } else {
        ElMessage.error(`删除药物不良反应记录失败: ${response.data.msg}`)
      }
    } catch (error) {
      console.error('删除药物不良反应记录时发生错误:', error)
      ElMessage.error('删除药物不良反应记录失败，请检查网络。')
    }
  }).catch(() => {
    ElMessage.info('已取消删除。')
  })
}

// 重置药物不良反应表单
const resetReactionForm = () => {
  reactionFormRef.value?.resetFields()
  Object.assign(reactionForm, {
    recordId: null,
    userId: null,
    reactionDate: null,
    reactionDescription: '',
    medicationInvolved: '',
    severity: '',
    notes: '',
  })
}

// --- 生命周期钩子和监听 ---
onMounted(() => {
  getPatientIdFromRoute()
  if (patientId.value) {
    fetchAttackRecords()
    fetchReactionRecords()
  }
})

// 监听路由参数变化，如果 patientId 改变则重新加载数据
watch(() => route.query.patientId, (newId) => {
  if (newId) {
    patientId.value = parseInt(newId);
    fetchAttackRecords();
    fetchReactionRecords();
  } else {
    patientId.value = null;
    attackRecords.value = [];
    reactionRecords.value = [];
  }
});
</script>

<template>
  <div class="patient-symptoms-reactions-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>患者症状及不良反应记录</span>
          <span v-if="patientId" class="patient-id-display"> (患者ID: {{ patientId }})</span>
          <span v-else class="patient-id-display" style="color: #f56c6c;"> 请从患者列表选择患者</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="犯病记录" name="attackRecords">
          <div class="table-toolbar">
            <el-button type="primary" @click="openAddAttackDialog" :disabled="!patientId">添加犯病记录</el-button>
          </div>
          <el-table :data="attackRecords" style="width: 100%" border>
            <el-table-column prop="recordId" label="记录ID" width="80"></el-table-column>
            <el-table-column prop="attackDate" label="犯病日期" width="180">
              <template #default="{ row }">
                {{ row.attackDate ? row.attackDate.split('T')[0] : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="attackType" label="犯病类型"></el-table-column>
            <el-table-column prop="attackDuration" label="持续时间"></el-table-column>
            <el-table-column prop="notes" label="备注"></el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="openEditAttackDialog(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteAttackRecord(scope.row.recordId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="药物不良反应" name="reactionRecords">
          <div class="table-toolbar">
            <el-button type="primary" @click="openAddReactionDialog" :disabled="!patientId">添加不良反应记录</el-button>
          </div>
          <el-table :data="reactionRecords" style="width: 100%" border>
            <el-table-column prop="recordId" label="记录ID" width="80"></el-table-column>
            <el-table-column prop="reactionDate" label="反应日期" width="180">
              <template #default="{ row }">
                {{ row.reactionDate ? row.reactionDate.split('T')[0] : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="reactionDescription" label="反应描述"></el-table-column>
            <el-table-column prop="medicationInvolved" label="涉及药物"></el-table-column>
            <el-table-column prop="severity" label="严重程度"></el-table-column>
            <el-table-column prop="notes" label="备注"></el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="openEditReactionDialog(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteReactionRecord(scope.row.recordId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
        v-model="attackFormDialogVisible"
        :title="isAttackEditing ? '编辑犯病记录' : '添加犯病记录'"
        width="500px"
        @close="resetAttackForm"
    >
      <el-form :model="attackForm" ref="attackFormRef" :rules="attackRules" label-width="120px">
        <el-form-item label="患者ID">
          <el-input v-model="attackForm.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="犯病日期" prop="attackDate">
          <el-date-picker
              v-model="attackForm.attackDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="犯病类型" prop="attackType">
          <el-input v-model="attackForm.attackType"></el-input>
        </el-form-item>
        <el-form-item label="持续时间" prop="attackDuration">
          <el-input v-model="attackForm.attackDuration"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="attackForm.notes" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="attackFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAttackForm">
            {{ isAttackEditing ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="reactionFormDialogVisible"
        :title="isReactionEditing ? '编辑药物不良反应记录' : '添加药物不良反应记录'"
        width="500px"
        @close="resetReactionForm"
    >
      <el-form :model="reactionForm" ref="reactionFormRef" :rules="reactionRules" label-width="140px">
        <el-form-item label="患者ID">
          <el-input v-model="reactionForm.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="反应日期" prop="reactionDate">
          <el-date-picker
              v-model="reactionForm.reactionDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="反应描述" prop="reactionDescription">
          <el-input type="textarea" v-model="reactionForm.reactionDescription" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="涉及药物" prop="medicationInvolved">
          <el-input v-model="reactionForm.medicationInvolved"></el-input>
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-select v-model="reactionForm.severity" placeholder="请选择严重程度" style="width: 100%;">
            <el-option label="轻微" value="轻微"></el-option>
            <el-option label="中度" value="中度"></el-option>
            <el-option label="严重" value="严重"></el-option>
            <el-option label="危及生命" value="危及生命"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="reactionForm.notes" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reactionFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReactionForm">
            {{ isReactionEditing ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
.patient-symptoms-reactions-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}
.patient-id-display {
  font-size: 14px;
  color: #606266;
  margin-left: 10px;
}
.box-card {
  max-width: 1200px;
  margin: 0 auto;
}
.table-toolbar {
  margin-bottom: 15px;
  text-align: right; /* 按钮靠右 */
}
</style>